package com.yx.accountBook.utils;

import com.yx.accountBook.common.Stack;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class HtmlUtils {

    public static List<String> getTableExtract(String content){
        List<String> resultTable = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        LinkedList<Integer> linkedListA = new LinkedList();
        LinkedList<Integer> linkedListB = new LinkedList();
        linkedListA = getIndexOfListByFind(content, linkedListA, 0, "<p class=\"yxui-thead\">");
        linkedListB = getIndexOfListByFind(content, linkedListB, 0, "<pre class=\"table-remark\">");
        LinkedList<Integer> resultList = new LinkedList();
        resultList.addAll(linkedListA);
        resultList.addAll(linkedListB);
        resultList.sort(Integer::compareTo);
        // 缓存 第一个出现的右边栈元素
        Integer cache = null;
        for (Integer subscript : resultList) {
            if (linkedListA.contains(subscript)) { // 如果是左边的就入栈
                stack.push(subscript);
                if (cache == null) {
                    cache = subscript;
                }
            }else if (linkedListB.contains(subscript)){ // 如果是右边的就出栈
                // 如果站内元素长度为 1 则取出数据
                if (stack.top() != null && stack.size() == 1) {
                    // 保存右边栈元素
                    String table = content.substring(cache, content.indexOf("</pre>", subscript) + 6);
                    table = table.replace("</pre>", "</p>");
                    table = table.replace("<pre class=\"table-remark\">", "<p class=\"table-remark\">");
                    if (table.contains("<table>")){
                        resultTable.add(table);
                    }
                    // 清空缓存左边的栈元素
                    cache = null;
                }
                // 出栈
                if (stack.size() != 0) {
                    stack.pop();
                }
            }
        }
        return resultTable;
    }

    public static LinkedList<Integer> getIndexOfListByFind(String content, LinkedList<Integer> listA, int subscript, String find){
        if (!StringUtils.isEmpty(find)) {
            int index = content.indexOf(find, subscript);
            if (index != -1){
                listA.add(index);
                getIndexOfListByFind(content, listA, index + 1, find);
            }
        }
        return listA;
    }



}
